package juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fangkun
 * @create 2022-12-07-13:48
 */
class MyNumber{

    private AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlus(){
        atomicInteger.incrementAndGet();
    }

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }
}

public class AtomicIntegerDemo {
    //100个线程，每个线程加5000次，CountDownLatch 等待上一个线程执行完毕
    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 1; i <= 100; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= 5000; j++) {
                        myNumber.addPlus();
                    }
                }finally {
                    countDownLatch.countDown();
                }

            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(myNumber.getAtomicInteger().get());
    }
}
